import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios'
import { Prompt } from '@kit.ArkUI';
import constants from './Constants';

/**
 * 网络请求工具
 * @author lijian
 */
const service = axios.create({
  baseURL: constants.BASE_URL,
  timeout: 60 * 1000
})

service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  if (config.method === 'get') {
    config.params = {
      _t: new Date().getTime() / 1000,
      ...config.params
    }
  }
  config.headers['ProjectsId'] = constants.PROJECTS_ID
  config.headers['App-Id'] = constants.APP_ID
  config.headers['App-Key'] = constants.APP_KEY
  config.headers['Sign'] = 'MD5='
  return config;
}, (error: AxiosError) => {
  return Promise.reject(error)
})

service.interceptors.response.use((response: AxiosResponse) => {
  if (response.data instanceof ArrayBuffer) {
    var resultBufferString = String.fromCharCode.apply(null, new Uint8Array(response.data))
    if (resultBufferString.toLocaleLowerCase().indexOf('png') > -1 ||
      resultBufferString.toLocaleLowerCase().indexOf('jfif') > -1) {
      /**
       *  const  buffer0=new Uint8Array(response.data as ArrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), '');
       let bufferBase64 = buffer.from(buffer0).toString('base64')
       return ("data:image/png;base64," + bufferBase64) as string
       */
      return response.data as ArrayBuffer
    } else {
      resultBufferString = decodeURIComponent(escape(resultBufferString))
      resultBufferString = JSON.parse(resultBufferString)
      Prompt.showToast({
        message: resultBufferString.data == null ? resultBufferString.message : resultBufferString.data
      })
    }
  } else {
    const res: HttpRes = response.data
    console.log('网络请求结果：' + JSON.stringify(res))
    if (res.code !== 200) {
      if (res.code === 500) {
      } else if (res.code === 501) {
      } else if (res.code === 506003) {
      } else {
        Prompt.showToast({
          message: res.data == null ? res.message : res.data
        })
      }
      return Promise.reject(res)
    } else {
      return res.data
    }

  }
  return response;
}, (error: AxiosError) => {
  Prompt.showToast({
    message: error.message === 'Network Error' ? '抱歉,服务忙,请稍后重试~' : error.message
  })
  return Promise.reject(error)
})

interface HttpRes<T = any> {
  code: number,
  message: string,
  success: boolean,
  data: T
}

export function httpGet<D = any>(url: string, params?: ESObject, headers?: ESObject): Promise<D> {
  return service({
    method: 'GET',
    url: url,
    params: params,
    headers: headers
  })
}

export function httpPost<D = any>(url: string, params?: ESObject, headers?: ESObject): Promise<D> {
  return service({
    method: 'POST',
    url: url,
    data: params,
    headers: headers
  })
}

export function pictureStream<D = any>(url: string, params?: ESObject, headers?: ESObject): Promise<D> {
  return service({
    method: 'GET',
    url: url,
    params: params,
    responseType: 'array_buffer'
  })
}